package com.zdf.license.verify.config;

import com.zdf.license.core.utils.Base64Utils;
import com.zdf.license.core.utils.CommonUtils;
import com.zdf.license.verify.model.LicenseVerifyManager;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;

/**
 * 检查证书
 * 1. 系统开启时加载证书
 * 2. 定时检查证书是否发生变化并且加载证书
 */
@EnableScheduling
public class CheckLicenseConfigure {

    private final LicenseVerifyProperties properties;

    public CheckLicenseConfigure(LicenseVerifyProperties properties){
        this.properties = properties;
    }

    /**文件唯一身份标识 == 相当于人类的指纹一样*/
    private String md5 = "";

    /** 5秒检测一次，不能太快也不能太慢 */
    @Scheduled(cron = "0/5 * * * * ?")
    public void checkLicense() {
        // 如果文件不存在就不需要校验了
        if (!checkLicenseExists()) {
            LicenseVerifyManager.simpleUninstall(properties.getVerifyParam());
            return;
        }
        String readMd5 = Base64Utils.getMd5(properties.getLicensePath());
        // 文件的MD5不相等，说明 license 变化了
        if(!readMd5.equals(md5)){
            LicenseVerifyManager.simpleInstall(properties.getVerifyParam());
            md5 = readMd5;
        }
    }

    private boolean checkLicenseExists(){
        if(CommonUtils.isEmpty(properties.getLicensePath())) {
            return false;
        }
        File licenseFile = new File(properties.getLicensePath());
        return licenseFile.exists();
    }

}
